package cn.org.dian.easycommunicate;

import java.util.List;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import cn.org.dian.easycommunicate.model.DataCenter;

public class SearchServiceActivity extends ListActivity {
    private static final String TAG = "SearchServiceActivity";
    private List<String> currentResultList = null;
    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        // setContentView(R.id.search_result_list);

        Intent intent = getIntent();

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            Log.d(TAG, "query: " + query);
            List<String> resultList = DataCenter.searchTerm(query);
            // if no search result 
            if (resultList.size() == 0) {
                resultList.add(getResources().getString(R.string.no_search_result));
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, 
                    resultList.toArray(new String[0]));
            setListAdapter(adapter);
            currentResultList = resultList;
        }
    }

    /* (non-Javadoc)
     * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        // get selected term name
        String selectedTermName = currentResultList.get(position);
        // test if term exist
        if (null == DataCenter.getTerm(selectedTermName)) {
            return;
        }
        Intent intent = new Intent(this, TermActivity.class);
        
        intent.putExtra("term_name", selectedTermName);
        startActivity(intent);
    }
    

}
